package com.isunland.managesystem.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.GridSecondViewAdapter;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.MyGridView;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.HintResponse;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.GuideMenu;
import com.isunland.managesystem.entity.GuideMenuNewOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.ConfigUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:  新版二级菜单
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/8 09:29
 */
public class GuideSecondFragment extends BaseFragment {

  private static String EXTRA_VALUE = GuideSecondListActivity.class.getSimpleName() + "EXTRA_VALUE";
  @BindView(R.id.ll_loading) LinearLayout llLoading;
  @BindView(R.id.gv) MyGridView gv;
  @BindView(R.id.fl_layout) FrameLayout flLayout;

  private GuideMenu mMenu;
  private ArrayList<GuideMenu> mList;
  private View mErrorView;  //错误视图
  private GridSecondViewAdapter mAdapter;

  public static GuideSecondFragment newInstance(GuideMenu menu) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_VALUE, menu);
    GuideSecondFragment fragment = new GuideSecondFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onStart() {
    volleyPostHint();// 提示数量
    super.onStart();
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mMenu = (GuideMenu) getArguments().getSerializable(EXTRA_VALUE);
    setTitleCustom(mMenu != null ? mMenu.getResName() : null);
    mList = new ArrayList<>();
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_guide_second, container, false);
    ButterKnife.bind(this, view);
    //错误视图
    mErrorView = View.inflate(getActivity(), R.layout.view_error, null);
    Button btnError = (Button) mErrorView.findViewById(R.id.btn_empty);
    flLayout.addView(mErrorView);
    llLoading.setVisibility(View.GONE);
    mErrorView.setVisibility(View.GONE);
    //空视图
    //View mEmptyView = LayoutInflater.from(getActivity()).inflate(R.layout.view_empty, null);
    //gv.setEmptyView(mEmptyView);

    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //跳转到二级菜单列表
        GuideMenu menu = mList.get(i);
        String flag = menu.getRoleTypeFlag();
        // 更新服务端类别参数.
        BaseVolleyActivity.setRoleTypeFlag(flag);
        mCurrentUser.setRoleTypeFlag(flag);
        int code = MyStringUtil.valueOfInt(menu.getAlias(), 0);
        if (ConfigUtil.get(mActivity, code) == null) {
          ToastUtil.show(R.string.wait_apps);
          return;
        }
        ConfigUtil.startByCode(mActivity, code);
      }
    });
    //获取二级菜单
    volleyPostGetMenu();
    btnError.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //获取二级菜单
        volleyPostGetMenu();
      }
    });
    return view;
  }

  private void volleyPostGetMenu() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_GUIDE_SECOND_MENU);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("parentid", mMenu.getResId());
    if (MyUtils.isNetLink(getActivity())) {

      llLoading.setVisibility(View.VISIBLE);
      mErrorView.setVisibility(View.GONE);
    } else {
      llLoading.setVisibility(View.GONE);
      mErrorView.setVisibility(View.VISIBLE);
    }
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        llLoading.setVisibility(View.GONE);
        mErrorView.setVisibility(View.VISIBLE);
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        // dialog消失
        llLoading.setVisibility(View.GONE);
        mErrorView.setVisibility(View.GONE);

        GuideMenuNewOriginal original = new Gson().fromJson(json, GuideMenuNewOriginal.class);

        if (original == null) {
          ToastUtil.show("解析数据为空，重新登录！");
          Intent i = new Intent(getActivity(), LoginActivity.class);
          startActivity(i);
        } else {
          String result = original.getResult();
          if (result.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(original.getMessage());
          } else {
            List<GuideMenu> rows = original.getRows();
            mList.clear();
            mList.addAll(rows);
            mAdapter = new GridSecondViewAdapter(getActivity(), mList);
            gv.setAdapter(mAdapter);
          }
        }
      }
    });
  }

  private void volleyPostHint() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_HINT_NUMBER);
    HashMap<String, String> params = new HashMap<>();
    mActivity.volleyPost(url, params, new HintResponse(mActivity, new HintResponse.CallBack() {
      @Override public void onSuccess() {
        if (mAdapter != null) mAdapter.notifyDataSetChanged();
      }
    }));
  }
}
